﻿using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Collections;
using System.Windows;

namespace NthDownload.Common.Interactivity.Behaviors
{
    public class ListBoxSelectedItemsBinder : Behavior<ListBox>
    {
        #region Override Methods

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.SelectionChanged -= ListBoxSelectionChanged;
            AssociatedObject.SelectionChanged += ListBoxSelectionChanged;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.SelectionChanged -= ListBoxSelectionChanged;
        }

        #endregion Override Methods

        #region Event Handlers

        private void ListBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedItems = AssociatedObject.SelectedItems;
        }

        #endregion Event Handlers

        #region Dependancy Properties

        public IList SelectedItems
        {
            get { return (IList)GetValue(SelectedItemsProperty); }
            set { SetValue(SelectedItemsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedItems.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedItemsProperty =
            DependencyProperty.Register("SelectedItems", typeof(IList), typeof(ListBoxSelectedItemsBinder), new PropertyMetadata(null));

        #endregion Dependancy Properties
    }
}
